<?php
declare(strict_types=1);

namespace App\Middleware\MchApi;

use App\Utils\CustomUtils;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Utils\Context;
use Phper666\JWTAuth\Exception\TokenValidException;
use Phper666\JWTAuth\JWT;
use Phper666\JWTAuth\Middleware\JWTAuthMiddleware;
use Phper666\JWTAuth\Util\JWTUtil;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Constants\XZXResponseCode;

class MchJWTAuthMiddleware extends JWTAuthMiddleware
{
    /**
     * @var HttpResponse
     */
    protected $response;

    protected $jwt;

    public function __construct(HttpResponse $response, JWT $jwt)
    {
        parent::__construct($response, $jwt);
    }

    /**
     * @param ServerRequestInterface  $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Throwable
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // $request = $request->withAttribute("ext", [
        //     "user"        => "",
        //     "createBy"    => "123",
        //     "uid"         => "123",
        //     "roleId"      => "",
        //     "isSuperRole" => true,
        //     "status"      => 1,
        //     "mchId"       => "6909D3D1-327C-F259-E612-E361FF897431",
        //     "mchNo"       => "M0017",
        //     "mch"         => [],
        //     "role"        => ""
        // ]);
        // $request = Context::set(ServerRequestInterface::class, $request);
        // return $handler->handle($request);

        $isValidToken = false;
        // $isApiType = false;
        // 根据具体业务判断逻辑走向，这里假设用户携带的token有效
        $token = $request->getHeaderLine('Authorization') ?? '';

        $data = null;

        if (strlen($token) > 0) {
            $token = JWTUtil::handleToken($token);
            $this->jwt->setScene("mchapi");
            if ($token !== false) {
                try {
                    $this->jwt->checkToken($token);
                } catch (\Throwable $th) {
                    //throw $th;
                    throw new TokenValidException(XZXResponseCode::getMessage(XZXResponseCode::TOKEN_EXPIRE_CODE), XZXResponseCode::TOKEN_EXPIRE_CODE);
                }
                $isValidToken = true;
            }

            $data = $this->jwt->getParserData();
            if($data['jwt_scene'] != 'mchapi')
            {
                $isValidToken = false;
            }
            if(!isset($data['user']->mchId))
            {
                //解密出来没有mchId 视为token无效
                $isValidToken = false;
            }
            CustomUtils::xzxDebug($data);
            // todo 用户状态检查

        }


        // 验token通过
        if ($isValidToken) {

            // $request->ext['createBy'] = $data['user']->username;
            // $request->ext['uid']   = $data['uid'];

            // CustomUtils::xzxDebug($request->ext);
            // // 读取商户信息
            // $mch = $this->MchInfoDao->get($user['mchId']);
            // $this->_verifyMchMerchant($mch);
            // $data['mch'] = array();

            // // 读取角色信息
            // $role = $this->MchRoleDao->get($user['roleId']);
            // $this->_verifyMchRole($role);
            // $data['role'] = array();

            $ext = array_merge($request->getAttribute("ext", []), [
                "user"        => $data,
                "createBy"    => $data['user']->username,
                "updateBy"    => $data['user']->username,
                "uid"         => $data['uid'],
                "roleId"      => $data['user']->roleId,
                "isSuperRole" => $data['user']->isSuperRole,
                "status"      => $data['user']->status,
                "mchId"       => $data['user']->mchId,
                "mchNo"       => $data['user']->mchNo,
                // "mch"         => $data['mch'],
                // "role"        => $data['role']
            ]);

            CustomUtils::xzxDebug($ext);

            // 全局修改$request，后面控制器需要接受ext
            $request = $request->withAttribute("ext", $ext);
            $request = Context::set(ServerRequestInterface::class, $request);

            return $handler->handle($request);

        } else {
            throw new TokenValidException(XZXResponseCode::getMessage(XZXResponseCode::TOKEN_ERROR_CODE), XZXResponseCode::TOKEN_ERROR_CODE);
        }
    }
}
